$(function () {
    initEmpGrid();

    initEvent();
})

var selectedEmpId = -1;
function initEmpGrid() {
    $.ajax({
        url: 'emp_list',
        type: 'post',
        dataType: 'json',
        success: function (result) {
            if (!result || !result.length) {
                return;
            }
            result.sort(function (a, b) {
                return a.uuid - b.uuid;
            });
            $('#grid').datagrid({
                data: result,
                singleSelect: true,
                fitColumns: true,
                columns: [[
                    {field: 'uuid', title: '编号', width: 100},
                    {field: 'name', title: '名称', width: 100}
                ]],
                onLoadSuccess: function () {
                    var rows = $('#grid').datagrid('getRows');
                    if (rows && rows.length) {
                        $('#grid').datagrid('selectRow', 0); //默认选中第一行
                        selectedEmpId = rows[0].uuid;
                        initMenuTree();
                    }
                },
                onClickRow: function (rowIndex, rowData) {
                    selectedEmpId = rowData.uuid;
                    initMenuTree();
                }
            })
        }
    });
}

function initMenuTree() {
    $.ajax({
        url: 'emp_readEmpRoles?id=' + selectedEmpId,
        type: 'post',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                var data = result.data;
                $('#tree').tree({
                    checkbox: true,
                    animate: true,
                    data: data
                });

            } else {
                $.messager.alert('提示', result.message, 'info', null);
            }
        }
    })
}

function initEvent() {
    $('#btnSave').bind('click', function () {
        var nodes = $('#tree').tree('getChecked');
        if (!nodes || !nodes.length) {
            $.messager.alert('提示', '请至少选中其中一项', 'info', null);
            return;
        }
        var ids = [];
        $.each(nodes, function (i, node) {
            ids.push(node.id);
        });
        var checkedStr = ids.join(',');
        $.ajax({
            url: 'emp_updateEmpRoles',
            type: 'post',
            data: {id: selectedEmpId, checkedStr: checkedStr},
            dataType: 'json',
            success: function (result) {
                $.messager.alert('提示', result.message, 'info', null);
            }
        })
    })
}